package com.ow.dva.module.front.controller;

import cn.hutool.core.util.NumberUtil;
import com.ow.dva.module.account.entity.AccountInfo;
import com.ow.dva.config.constant.UserConstant;
import com.ow.dva.config.shiro.ShiroAccount;
import com.ow.dva.module.account.entity.AccountPark;
import com.ow.dva.module.account.service.AccountInfoService;
import com.ow.dva.module.account.service.AccountParkService;
import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.base.entity.param.DvaPage;
import com.ow.dva.module.front.entity.Fold;
import com.ow.dva.module.order.entity.Order;
import com.ow.dva.module.order.service.OrderService;
import com.ow.dva.module.park.entity.Park;
import com.ow.dva.module.park.service.ParkService;
import com.ow.dva.module.passingRecord.entity.PassingRecord;
import com.ow.dva.module.passingRecord.service.PassingRecordService;
import com.ow.dva.util.DateOfMonth;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/front")
public class FrontController {


    /**
     * 描述： 停车场管理员登录
     * 创建时间：2020/5/12  YanZengBao
     * 修改时间：2020/5/12  YanZengBao 加注释
     * 修改时间：
     */
    @PostMapping(value="/parkManagerLogin")
    @ResponseBody
    public RT parkManagerLogin(String userName,String password, HttpSession session){
        if(!userName.isEmpty() && !password.isEmpty()){
            //获取当前会话主体
            Subject subject = SecurityUtils.getSubject();
            //获取token
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            try {
                //登陆
                subject.login(token);
            } catch (UnknownAccountException e) {
                return RT.error(1,"您的账号不存在！");
            }catch (IncorrectCredentialsException e) {
                return RT.error(2,"您的账号/密码 错误！");
            }catch (LockedAccountException e) {
                return RT.error(4,"您的账号账户已禁用！");
            } catch (AuthenticationException e) {
                return RT.error(3,"您的账号没有权限登录此平台！");
            }
            //如果登陆成功
            if (subject.isAuthenticated()) {
                ShiroAccount shiroAccount = (ShiroAccount) subject.getPrincipal();
                initSession(session, shiroAccount);
                return RT.ok("登录成功！");
            }
        }
        return RT.error(10,"登录失败！");
    }

    /**
     * 用户信息存入session
     */
    private void initSession(HttpSession session,ShiroAccount shiroAccount) {
        //存入用户
        session.setAttribute(UserConstant.ACCOUNT,shiroAccount.getAccount());
        //存入accountInfo
        if(shiroAccount.getAccountInfo() != null){
            session.setAttribute(UserConstant.ACCOUNT_INFO,shiroAccount.getAccountInfo());
        }
    }

    /**
     * 注销登陆
     * @param session
     * @return
     */
    @GetMapping(value="/logout")
    public String logout(HttpSession session){
        try {
            session.removeAttribute(UserConstant.ACCOUNT);
            session.removeAttribute(UserConstant.ACCOUNT_INFO);
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/login/";
    }


    /**
     * zsj
     * 查单个停车场时传parkId，根据帐号查传accountId
     * @param accountId
     * @param parkId
     * @return
     */
    @RequestMapping("/getPart")
    @ResponseBody
    public RT getPart (String accountId, String parkId){
        List<Park> parks = new ArrayList<>();
        if (parkId!=null){
            Park park = parkService.getById(parkId);
            parks.add(park);
        }else {
            List<AccountPark> accountParks = accountParkService.getByAccountId(accountId);
            if (accountParks != null && accountParks.size()!=0){
                for (AccountPark accountPark : accountParks){
                    Park park = parkService.getById(accountPark.getParkId());
                    parks.add(park);
                }
            }
        }
        AccountInfo accountInfo = accountInfoService.findByAccountId(accountId);
        Map map = new HashMap();
        map.put("city",accountInfo.getCity());
        map.put("parks",parks);
        return RT.ok(map);
    }

    /**
     * zsj
     * 根据车牌号模糊匹配
     * 根据车牌号 停车场id查询最近7天的出入场记录
     * @param parkId
     * @param plateNo
     * @return
     */
    @RequestMapping("/getPassRecordByPlate")
    @ResponseBody
    public RT getPassRecord (String parkId, String plateNo){
        List<PassingRecord> passingRecords = passingRecordService.getWeekRecordByPlate(parkId,plateNo);
        if (passingRecords!=null && passingRecords.size()!=0){
            return RT.ok(passingRecords);
        }else {
            return RT.error(1,"没有数据！");
        }

    }

    /**
     * zsj
     * 获取过车记录地图标点
     * @param parkId 可空
     * @param plateNo
     * @return
     */
    @RequestMapping("/getPassRecordByPlateMarker")
    @ResponseBody
    public RT getPassRecordByPlateMarker (String parkId, String plateNo){
        if ("".equals(parkId)){
            parkId = null;
        }
        List<PassingRecord> passingRecords = passingRecordService.getPassRecordByPlateMarker(parkId,plateNo);
        if (passingRecords!=null && passingRecords.size()!=0){
            return RT.ok(passingRecords);
        }else {
            return RT.error(1,"没有数据！");
        }
    }

    /**
     * zsj
     * 近期车流量统计 7天 折线
     * @param parkId
     * @return
     */
    @RequestMapping("/countPassRecordByPark")
    @ResponseBody
    public RT countPassRecordByPark(String parkId){
        List<Fold> folds = passingRecordService.countPassRecordByPark(parkId);
        return RT.ok(folds);
    }

    /**
     * zsj
     * 近期订单统计 7天 折线
     * @param parkId
     * @return
     */
    @RequestMapping("/countOrderByPark")
    @ResponseBody
    public RT countOrderByPark(String parkId){
        List<Fold> folds = orderService.countOrderByPark(parkId);
        return RT.ok(folds);
    }

    /**
     * 获取最新过车记录（单条）
     * @param parkId 停车场id
     * @param direction 方向 0-入 1-出
     * @return
     */
    @RequestMapping("/getPassRecordByPark")
    @ResponseBody
    public RT getPassRecordByPark(String parkId, int direction){
        PassingRecord passingRecords = passingRecordService.getNewPassRecordByPark(parkId,direction);
        return RT.ok(passingRecords);
    }

    /**
     * @author  姜延鹏
     * @Description  停车场Tree
     * @param accountId
     * @date  2020/5/11
     * @return  java.util.Map
     */
    @RequestMapping(value = "/getParkTree")
    public String getParkTree(String accountId, Model model){

        List<Park> closeParks = new ArrayList<>();
        List<Park> roadsideParks = new ArrayList<>();

        List<AccountPark> accountParks = accountParkService.getByAccountId(accountId);
        for (AccountPark accountPark : accountParks) {
            Park park = parkService.getById(accountPark.getParkId());
            if (park.getParkType()==0){
                closeParks.add(park);
            }else if (park.getParkType()==1){
                roadsideParks.add(park);
            }
        }

        Map map = new HashMap();
        map.put("closeParks",closeParks);
        map.put("roadsideParks",roadsideParks);

        model.addAttribute("map",map);

        return "front/parkTree";
    }


    /**
     * @author  姜延鹏
     * @Description  全部停车场7天历史订单
     * @param accountId
     * @date  2020/5/11
     * @return  java.util.List<com.ow.dva.module.order.entity.Order>

     */
    @RequestMapping(value = "/getHistoryOrder")
    @ResponseBody
    public RT getHistoryOrder(String accountId) {

        List<AccountPark> accountParks = accountParkService.getByAccountId(accountId);
        List<Order> orders = new ArrayList<>();

        Map map = new HashMap();
        for (AccountPark accountPark : accountParks){
            int today = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
            map.put("parkId", accountPark.getParkId());
            List<Order> orderLists = orderService.sevenDayOrdersByPark(map);
            orders.addAll(orderLists);

        }

        List<Fold> foldList = new ArrayList<>();
        Calendar cale = Calendar.getInstance();
        Integer month = cale.get(Calendar.MONTH) + 1;

        DateOfMonth dates = new DateOfMonth();
        for (int i = 0; i < 7; i++) {
            int weight = dates.getVerify(i);
            Fold fold = new Fold();
            Integer counts = 0;
            for (Order o : orders) {
                int day = o.getCreateTime().getDate();
                if (day == weight) {
                    counts=counts+1;
                }
            }
            fold.setAxis(month+"月"+weight+"日");
            fold.setValue(counts+"");
            foldList.add(fold);
        }

        Collections.reverse(foldList);

        return RT.ok(foldList);
    }


    /**
     * @author 姜延鹏
     * @param accountId
     * @return java.util.List<java.util.Map>
     * @Description 今日各停车场车流量统计
     * @date 2020/5/11
     */
    @RequestMapping(value = "/getTodays")
    @ResponseBody
    public RT getTodays(String accountId) {


        List<Fold> foldList = new ArrayList<>();

        List<AccountPark> accountParks = accountParkService.getByAccountId(accountId);
        for (AccountPark accountPark : accountParks) {
            Fold fold = new Fold();
            List<PassingRecord> passingRecords = passingRecordService.getTodayByPark(accountPark.getParkId());
            Park park = parkService.getById(accountPark.getParkId());
            fold.setAxis(park.getName());
            fold.setValue(passingRecords.size()+"");
            foldList.add(fold);
        }
        return RT.ok(foldList);
    }

    /**
     * @author  姜延鹏
     * @Description  全部停车场7天历史车流量
     * @param accountId
     * @date  2020/5/11
     * @return  java.util.List<java.util.Map>
     */
    @RequestMapping(value = "/getHistorys")
    @ResponseBody
    public RT getHistorys(String accountId){


        List<PassingRecord> passingRecordList = new ArrayList<>();
        DateOfMonth dates = new DateOfMonth();
        List<AccountPark> accountParks = accountParkService.getByAccountId(accountId);
        for (AccountPark accountPark : accountParks) {
            List<PassingRecord> passingRecords = passingRecordService.weekDataByPark(accountPark.getParkId());
            passingRecordList.addAll(passingRecords);
        }

        List<Fold> foldList = new ArrayList<>();
        Calendar cale = Calendar.getInstance();
        Integer month = cale.get(Calendar.MONTH) + 1;
        for (int i=0; i<7; i++){
            Fold fold = new Fold();
            Integer counts = 0;
            int weight = dates.getVerify(i);
            for (PassingRecord passingRecord : passingRecordList){
                int day = passingRecord.getCreateTime().getDate();
                if (day == weight){
                    counts = counts+1;
                }
            }
            fold.setAxis(month+"月"+weight+"日");
            fold.setValue(counts+"");
            foldList.add(fold);
        }
        Collections.reverse(foldList);
        return RT.ok(foldList);
    }

    /**
     * @author  姜延鹏
     * @Description  最新记录10条
     * @param accountId
     * @date  2020/5/11
     * @return  com.ow.dva.module.base.entity.json.RT
     */
    @RequestMapping(value = "/getNewPassingRecord")
    @ResponseBody
    public RT getNewPassingRecord(String accountId){
        List list = new ArrayList<>();
        List<AccountPark> accountParks = accountParkService.getByAccountId(accountId);
        for (AccountPark accountPark : accountParks) {
            list.add(accountPark.getParkId());
        }
        List<PassingRecord> passingRecords = passingRecordService.getNewPassingRecord(list);

        return RT.ok(passingRecords);
    }

    /**
     * 描述：今日车流量（统计入场）
     * 创建时间：2020/5/13  YanZengBao
     * 修改时间：2020/5/13  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/countTodayPassRecord")
    @ResponseBody
    public RT countTodayPassRecord(String accountId){
        int count = 0;
        List<AccountPark> list = accountParkService.getByAccountId(accountId);
        if(list != null && !list.isEmpty()){
            for (AccountPark ap: list) {
                List<PassingRecord> todayByPark = passingRecordService.getTodayByPark(ap.getParkId());
                //System.out.println("今日入场数：" + todayByPark.size());
                count += todayByPark.size();
            }
        }
        return RT.ok(count);
    }

    /**
     * 描述： 今日订单量（全部）
     * 创建时间：2020/5/13  YanZengBao
     * 修改时间：2020/5/13  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/countTodayOrder")
    @ResponseBody
    public RT countTodayOrder(String accountId){
        int count = 0;
        List<AccountPark> list = accountParkService.getByAccountId(accountId);
        if(list != null && !list.isEmpty()){
            for (AccountPark ap: list) {
                List<Order> allTodayOrders = orderService.getAllTodayOrdersByParkId1(ap.getParkId());
                //System.out.println("今日全部订单数：" + allTodayOrders.size());
                count += allTodayOrders.size();
            }
        }
        return RT.ok(count);
    }

    /**
     * 描述： 今日收费统计（全部）（帐号）
     * 创建时间：2020/5/13  YanZengBao
     * 修改时间：2020/5/13  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/countAllMoney")
    @ResponseBody
    public RT countAllMoney(String accountId){
        double count = 0.0;
        List<AccountPark> list = accountParkService.getByAccountId(accountId);
        if(list != null && !list.isEmpty()){
            for (AccountPark ap: list) {
                List<Order> allTodayOrders = orderService.getAllTodayOrdersByParkId(ap.getParkId());
                if(allTodayOrders != null && !allTodayOrders.isEmpty()){
                    for (Order order:allTodayOrders) {
                        count += order.getReallyMoney();
                    }
                }
            }
        }
        BigDecimal round = NumberUtil.round(count, 2);
        return RT.ok(round);
    }

    /**
     * 描述：  总车位数/剩余车位数（全部&&帐号）
     * 创建时间：2020/5/13  YanZengBao
     * 修改时间：2020/5/13  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/countParkinglot")
    @ResponseBody
    public RT countParkinglot(String accountId){
        Map map = new HashMap();
        int allParkinglot = 0;
        int allSurplus = 0;
        List<AccountPark> list = accountParkService.getByAccountId(accountId);
        if(list != null && !list.isEmpty()){
            for (AccountPark ap: list) {
                Park park = parkService.getById(ap.getParkId());
                if(park != null){
                    allParkinglot += park.getParkinglotTotal();
                    allSurplus += park.getParkinglotSurplus();
                }
            }
        }
        map.put("allParkinglot",allParkinglot);
        map.put("allSurplus",allSurplus);
        return RT.ok(map);
    }


    /**
     * 描述： 条件查询过车记录
     * 创建时间：2020/5/13  YanZengBao
     * 修改时间：2020/5/13  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/passingRecord")
    @ResponseBody
    public RT passingRecord(DvaPage<PassingRecord> dvaPage, @RequestParam Map<String, Object> param){

        String accountId = (String)param.get("accountId");
        List<String> parkIds = new ArrayList<>();
        List<AccountPark> list = accountParkService.getByAccountId(accountId);
        if(list != null && !list.isEmpty()){
            for (AccountPark ap: list) {
                Park park = parkService.getById(ap.getParkId());
                if(park != null){
                    parkIds.add(park.getId());
                }
            }
        }
        param.put("parkIds",parkIds);
        DvaPage<PassingRecord> page = passingRecordService.page(dvaPage,param);
        return RT.ok(page);
    }



    /**
     * 测试前台页面
     * @return
     */
    @RequestMapping("/testRecordMap")
    public String testFront(){

        return "front/record-map";
    }

    @RequestMapping("/testParkMap")
    public String testParkMap(){

        return "front/park-map";
    }

    @RequestMapping("/testEcharsMap")
    public String testEcharsMap(){

        return "front/echars-map";
    }


    @RequestMapping("/testCount")
    public String testCount(){

        return "front/indexCount";
    }


    @Resource
    private ParkService parkService;
    @Resource
    private PassingRecordService passingRecordService;
    @Resource
    private AccountParkService accountParkService;
    @Resource
    private OrderService orderService;
    @Resource
    private AccountInfoService accountInfoService;
}
